"use client"; // 必须要添加
import {useState} from 'react'
import { navs } from "./config";
import styles from "./index.module.scss";
import Link from "next/link";
import { NextPage } from "next";
import { message} from 'antd'
import {usePathname } from "next/navigation";
import { Button,Avatar,Dropdown,Menu } from "antd";
import Login from 'components/Login'
import { useStore } from 'store/index'
import request from 'service/fetch'
import { LoginOutlined,HomeOutlined} from "@ant-design/icons";

const Navbar:NextPage = () =>{
  const pathname = usePathname()
  const [isShowLogin,setIsShowLogin] = useState(false)
  const handleGoEditorPage = () =>{

  }
  const handleLogin = () =>{
    setIsShowLogin(true)
  }
  const handleClose = () =>{
    setIsShowLogin(false)
  }
  const renderDropDownMenu = () => {
    return (
      <Menu>
        <Menu.Item><HomeOutlined/>&nbsp;个人主页</Menu.Item>
        <Menu.Item onClick={handleLogout}><LoginOutlined />&nbsp;退出</Menu.Item>
      </Menu>
    )
  }
  const store = useStore()
  const {userId,avatar } = store.user.userInfo
  // 退出
  const  handleLogout  = () =>{
    request.post('/api/loginout').then((res: any)=>{
      if(res?.code === 0){
          message.success(res.msg)
          store.user.setUserInfo({})
      }else{
         message.error(res?.msg || '未知错误')
      }
  })

    
  }
  // 参考文档
  // https://nextjs.org/docs/app/api-reference/functions/use-router
    return (
      <div className={styles.navbar}>
        <section className={styles.logArea}>BLOG-C</section>
        <section className={styles.linkArea}>
           { navs?.map((nav)=>{
             return <Link className={pathname === nav.value ? styles.active : ''} key={nav?.label} href={nav?.value}>
              {nav?.label}
             </Link>
            })}
        </section>
        <section className={styles.operationArea}>
          <Button onClick={handleGoEditorPage}>写文章</Button>
            {
              userId ? (
                <>
                <Dropdown overlay={renderDropDownMenu()} placement='bottomLeft'>
                  <Avatar src={avatar} size={32}></Avatar>
                </Dropdown>
                </>
              ) :   <Button type="primary" onClick={handleLogin}>登录</Button>
            }
        
        </section>
        <Login isShow={isShowLogin} onClose={handleClose}></Login>
      </div>
    );
  }

  export default Navbar
  